import { showToast } from 'vant'
// 导入 axios
import axios from 'axios'
// 引入 vuex
import store from '../store/index.js'
import router from '../router'

// 配置 axios
axios.defaults.baseURL = '/api'
axios.defaults.headers = {
    'Content-Type': 'application/x-www-form-urlencoded'
}

// 请求拦截器
axios.interceptors.request.use(
        (config) => {
            store.commit('showLoading')
                // 若请求的不是 /login 的接口，需要对 token 进行判断
            if (
                config.url !== '/checkcode/pic' &&
                config.url !== '/checkcode/verify' &&
                config.url !== '/auth/oauth/token'
            ) {
                const token = window.sessionStorage.getItem('token')
                if (token) {
                    config.headers.Authorization = `Bearer ${token}`
                } else {
                    window.sessionStorage.removeItem('token')
                    router.push('/login')
                }
            }
            return config
        },
        (error) => {
            store.commit('hideLoading')
            return Promise.reject(error)
        }
    )
    // 响应拦截器
axios.interceptors.response.use(
    (response) => {
        store.commit('hideLoading')
        if (response.data.code === 401) {
            showToast('登录失效，请重新登录！')
            return router.push('/login')
        }
        return response
    },
    (error) => {
        store.commit('hideLoading')
        return Promise.reject(error)
    }
)